package com.adu.springRedis.service.Imp;

import com.adu.springRedis.domain.User;
import com.adu.springRedis.mapper.UserMapper;
import com.adu.springRedis.service.UserService;

import com.adu.springRedis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class IUserService implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }
    // 根据id查询记录
    @Override
    public User find(int id) {
        long beginTime=System.currentTimeMillis();
        //根据key查询缓存
        User user=(User) redisUtil.getValue("userKey"+id);
        //判断是否为空
        if(user==null){
            // 缓存为空，查询数据库
            user=userMapper.find(id);
            System.out.println("缓存为空，查询数据库");
            // 插入缓存,并设置过期时间（单位为秒）
//            redisUtil.setValueAndExpire("userKey"+id,user,30);
            redisUtil.setValue("userKey"+id,user);
            System.out.println("插入缓存");
        }else{
            System.out.println("缓存不为空");
        }
        long endTime=System.currentTimeMillis();
        System.out.println("总用时："+(endTime-beginTime));
        return user;
    }

    @Override
    public void remove(int id){
        // 删除缓存
        redisUtil.deleteValue("userKey"+id);
        //删除数据库数据
        userMapper.remove(id);
    }

    @Override
    public void update(User user){
        userMapper.update(user);
    }
}